package com.blb.day2;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 银行类
 */
public class Bank {

//    Object lock = new Object();

    Lock lock = new ReentrantLock();

    //100个银行账户
    public int[] accounts = new int[100];

    public Bank(){
        //初始化银行账户
        for (int i = 0;i < accounts.length;i++){
            accounts[i] = 1000;
        }
    }

    /**
     * 转账
     */
    public void transfer(int out,int in,int money){
        if(accounts[out] < money){
            throw new RuntimeException("银行账户余额不足");
        }
        lock.lock();
        try {
//        synchronized(lock) {
            accounts[out] -= money;
            System.out.println("账户" + out + "转出" + money);
            accounts[in] += money;
            if (new Random().nextInt(5) == 0) {
                throw new RuntimeException("error");
            }
            System.out.println("账户" + in + "转入" + money);
            System.out.println("银行总金额是：" + calc());
//        }
        }finally {
            lock.unlock();
        }
    }

    /**
     * 计算总余额
     * @return
     */
    public int calc(){
        int sum = 0;
        for(int i = 0;i < accounts.length;i++){
            sum += accounts[i];
        }
        return sum;
    }
}
